<?php
class Signup extends CustomerController {
    public function __construct() {
        parent::__construct();
    }
    
    public function index() {
        $this->_data["loadPage"]="verify/signup_view";
        $this->_data["loadMenu"]="other/menu_view";
        $this->_data["titlePage"]="Đăng ký";
        
        $this->load->model("mmodule");
        $tmp=$this->mmodule->listAll();
        if($tmp!=false)
        $this->_data["info_module"]=$tmp;
        
        //load level
        $this->load->model("mlevel");
        $level=$this->mlevel->getByName("customer");
        $level_id=$level["level_id"];
        
        //validation and add
        $this->load->helper("form");
        $this->load->library("form_validation");
        $this->form_validation->CI =& $this;
        
        $config=array(
            array(
                "field"=>"txtUsername",
                "label"=>"Username",
                "rules"=>"required|callback_checkUsername"
            ),
            array(
                "field"=>"txtEmail",
                "label"=>"Email",
                "rules"=>"required|callback_checkEmail"
            )
        );
        $this->form_validation->set_rules($config);
        
        //update
        if($this->form_validation->run()) {
            $username=$this->input->post("txtUsername");
            $pass=$this->input->post("txtPass");
            $fullname=$this->input->post("txtFullname");
            $address=$this->input->post("txtAddress");
            $phone=$this->input->post("txtPhone");
            $email=$this->input->post("txtEmail");
            $this->load->model("muser");
            $data=array(
                "u_username"=>$username,
                "u_password"=>md5($pass),
                "u_fullname"=>$fullname,
                "u_address"=>$address,
                "u_phone"=>$phone,
                "u_email"=>$email,
                "level_id"=>$level_id
            );
            $this->muser->insert($data);
            $this->session->set_flashdata("flash_mess", "Đăng ký user thành công.");
            redirect(base_url().$this->_data["module"]."/login");
        }
        
        $this->load->view($this->_data["path"], $this->_data);
    }
    
    public function checkUsername($username) {
        $this->load->model("muser");
        $id=$this->uri->segment(4);
        if(!$this->muser->checkUsername($username, $id)) {
            $this->form_validation->set_message("checkUsername", "Tên đăng nhập này đã được đăng ký!");
            return false;
        }else
            return true;
    }
    
    public function checkEmail($email) {
        $this->load->model("muser");
        $id=$this->uri->segment(4);
        if(!$this->muser->checkEmail($email, $id)) {
            $this->form_validation->set_message("checkEmail", "Email này đã được đăng ký!");
            return false;
        }else
            return true;
    }
}
?>
